<template>
  <div id="addQuestionView">
    <h2>创建题目</h2>
    <a-form :model="form" label-align="right">
      <a-form-item
        field="title"
        label="标题"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input
          v-model="form.title"
          placeholder="请输入标题"
          class="aligned-input"
        />
      </a-form-item>
      <a-form-item
        field="tags"
        label="标签"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-input-tag
          v-model="form.tags"
          placeholder="请选择标签"
          allow-clear
          class="aligned-input"
        />
      </a-form-item>
      <a-form-item
        field="content"
        label="题目内容"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <MdEditor
          :value="form.content"
          :handle-change="onContentChange"
          class="aligned-input"
        />
      </a-form-item>
      <a-form-item
        field="answer"
        label="答案"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <MdEditor
          :value="form.answer"
          :handle-change="onAnswerChange"
          class="aligned-input"
        />
      </a-form-item>
      <a-form-item
        label="判题配置"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <a-space direction="vertical">
          <a-form-item
            field="judgeConfig.timeLimit"
            label="时间限制(ms)"
            label-col="100px"
            wrapper-col="calc(100% - 100px - 8px)"
          >
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              mode="button"
              min="0"
              class="aligned-input"
            />
          </a-form-item>
          <a-form-item
            field="judgeConfig.memoryLimit"
            label="内存限制(KB)"
            label-col="100px"
            wrapper-col="calc(100% - 100px - 8px)"
          >
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              mode="button"
              min="0"
              class="aligned-input"
            />
          </a-form-item>
          <a-form-item
            field="judgeConfig.stackLimit"
            label="堆栈限制(KB)"
            label-col="100px"
            wrapper-col="calc(100% - 100px - 8px)"
          >
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              mode="button"
              min="0"
              class="aligned-input"
            />
          </a-form-item>
        </a-space>
      </a-form-item>
      <a-form-item
        label="测试用例配置"
        label-col="80px"
        wrapper-col="calc(100% - 80px - 8px)"
      >
        <!-- 测试用例容器 -->
        <div class="test-case-container">
          <div
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :key="index"
            class="test-case"
          >
            <a-form-item
              :field="`form.judgeCase[${index}].input`"
              :label="`输入用例-${index + 1}`"
              label-col="100px"
              wrapper-col="calc(100% - 100px - 8px)"
              no-style
            >
              <a-input
                v-model="judgeCaseItem.input"
                placeholder="测试输入用例"
                class="aligned-input"
              />
            </a-form-item>
            <a-form-item
              :field="`form.judgeCase[${index}].output`"
              :label="`输出用例-${index + 1}`"
              label-col="100px"
              wrapper-col="calc(100% - 100px - 8px)"
              no-style
            >
              <a-input
                v-model="judgeCaseItem.output"
                placeholder="测试输出用例"
                class="aligned-input"
              />
            </a-form-item>
            <!-- 删除按钮放在每个测试用例的末尾 -->
            <div class="test-case-actions">
              <a-button
                status="danger"
                @click="handleDelete(index)"
                class="delete-btn"
              >
                删除
              </a-button>
            </div>
          </div>
        </div>

        <!-- 新增按钮固定在所有测试用例下方 -->
        <div class="add-button-container">
          <a-button
            @click="handleAdd"
            type="outline"
            status="success"
            class="add-btn"
          >
            新增测试用例
          </a-button>
        </div>
      </a-form-item>
      <a-form-item label-col="80px" wrapper-col="calc(100% - 80px - 8px)">
        <a-button @click="doSubmit" class="custom-submit-btn">
          {{ updatePage ? "更新题目" : "提交" }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute } from "vue-router";

const route = useRoute();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

let form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  console.log(form.value);
  // 区分更新还是创建
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("更新成功");
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("创建成功");
    } else {
      message.error("创建失败，" + res.message);
    }
  }
};

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

const onContentChange = (value: string) => {
  form.value.content = value;
};

const onAnswerChange = (value: string) => {
  form.value.answer = value;
};
</script>

<style scoped>
#addQuestionView {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.aligned-input {
  width: 100% !important;
  max-width: 600px;
}

.arco-form-item-label {
  padding-right: 8px !important;
  text-align: right !important;
}

.arco-form-item-control-wrapper {
  margin-left: 0 !important;
}

/* 测试用例样式调整 */
.test-case-container {
  margin-bottom: 16px;
}

.test-case {
  margin-bottom: 24px; /* 测试用例之间的间距 */
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.test-case-actions {
  margin-top: 12px;
  text-align: right; /* 右对齐删除按钮 */
}

.delete-btn {
  min-width: 80px;
}

.add-button-container {
  margin-top: 16px;
  text-align: right; /* 右对齐新增按钮 */
}

.add-btn {
  min-width: 120px;
}

.custom-submit-btn {
  background-color: #f5f5f5 !important;
  color: #00b42a !important;
  border: 1px solid #e5e6eb !important;
  min-width: 150px;
  padding: 6px 16px;
}

.custom-submit-btn:hover {
  background-color: #eeeeee !important;
}
</style>
